package xyz.syyrjx.call.factory;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import xyz.syyrjx.call.proxy.SyyrjxRpcCallClientProxy;
import xyz.syyrjx.consumer.client.SyyrjxRpcConsumerClient;

import java.lang.reflect.Constructor;
import java.lang.reflect.Proxy;

/**
 * @author 大地崩坏苍蝇兽
 * @date 2023/1/22 - 15:26
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class SyyrjxRpcCallClientFactoryBean implements FactoryBean<Object>, InitializingBean {

    private Class<?> interfaceClass;

    private boolean needFallback;

    private long timeout;

    private Class<? extends Exception>[] ignoreExceptions;

    @Override
    public Object getObject() throws Exception {
        SyyrjxRpcCallClientProxy proxy = new SyyrjxRpcCallClientProxy();
        proxy.setInterfaceClass(interfaceClass);
        if (needFallback) {
            String fallbackClassName = interfaceClass.getName() + "Fallback";
            Class<?> fallbackClass = Class.forName(fallbackClassName);
            Object fallbackEntity = fallbackClass.getConstructor().newInstance();
            proxy.setFallbackEntity(fallbackEntity);
            proxy.setIgnoreExpects(ignoreExceptions);
            proxy.setTimeout(timeout);
        }

        return Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass}, proxy);
    }

    @Override
    public Class<?> getObjectType() {
        return interfaceClass;
    }

    @Override
    public void afterPropertiesSet() throws Exception {

    }
}
